use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .create_table(
                Table::create()
                    .table(ModelHasPermissions::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(ModelHasPermissions::PermissionId)
                            .string()
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(ModelHasPermissions::ModelType)
                            .string()
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(ModelHasPermissions::ModelId)
                            .string()
                            .not_null(),
                    )
                    .primary_key(
                        Index::create()
                            .col(ModelHasPermissions::PermissionId)
                            .col(ModelHasPermissions::ModelType)
                            .col(ModelHasPermissions::ModelId),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk_model_has_permissions_permission_id")
                            .from(
                                ModelHasPermissions::Table,
                                ModelHasPermissions::PermissionId,
                            )
                            .to(Permissions::Table, Permissions::Id)
                            .on_delete(ForeignKeyAction::Cascade)
                            .on_update(ForeignKeyAction::Restrict),
                    )
                    .to_owned(),
            )
            .await
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .drop_table(Table::drop().table(ModelHasPermissions::Table).to_owned())
            .await
    }
}

#[derive(DeriveIden)]
enum ModelHasPermissions {
    Table,
    PermissionId,
    ModelType,
    ModelId,
}

#[derive(DeriveIden)]
enum Permissions {
    Table,
    Id,
}
